#!/usr/bin/env python

"""
service.py

Created Dan Guido on 2009-05-18.
"""

# http://docs.python.org/library/xml.etree.elementtree.html
import xml.etree.ElementTree as ET
import hashlib
import urllib
import urllib2

# 3rd party modules for multipart/form-data uploads
# http://atlee.ca/software/poster/index.html
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

# MIR modules
from common.py import getMeta

class service:
	"""
	This class defines a simple web service we can post files to
	and get reports from.
	"""
	
	def __init__(self, filepath, hashes):
		root = ET.parse(filepath).getroot()
		
	# pre-condition: given a file
	# post-condition: returns report URL if found, false otherwise
	# bugs: only handles GET, checks success via URI
	def search(self, filepath):
		search = root.find('search')
		
		# if search isn't defined we can stop here
		if not search or search is None:
			return False
		
		# get the URL to search
		url = search.find("search_url")
		
		# get the variables
		variables = search.find('variables')
		for param in variables.getchildren('variables'):
			# build a dictionary
			# post_data = {}
		
		# send the variables over to be replaced by user intent
		buildPayload(post_data)
		
		# urlencode the data
		encoded_data = urllib.urlencode(post_data)
				
		try:
			response = urllib2.urlopen(request)
		except URLError, e:
			print "Error: " + e.strerror
			print "Searching for existing " + " " + " reports failed."
			return False
		
		# get criteria for successful searches
		success = search.find('success')
		
		# the URI indicates success/failure
		if success.get('method') is 'uri':
			result = response.geturl()
			# simple string matching
			if success.get('type') is 'string':
				if success.text in result:
					return result
				return False
			else if success.get('type') is 'regexp':
				# not supported yet
				pass
	
		not supported yet
		else if success.get('method') is 'content':
			pass
			
		return False
		
	# pre-condition: given a file
	# post-condition: returns a report URL, exceptions otherwise
	def submit(self, filepath):
		pass
	
	# post-condition: returns the name of the service being used
	def getName(self):
		pass
	
	# pre-condition: given a filepath
	# post-condition: returns true/false based on type and size
	def isAllowedFile(self, filename):
		pass
		
	# pre-condition: 'intent' is a global dictionary and post_data is
	# a dictionary of potential replacements for this service
	# post-condition: values in post_data have been replaced based on
	# user intent
	def buildPayload(self, post_data):
		pass
		
if __name__ == '__main__':
	pass